﻿/*
#**************************************************************************
#  openSIS is a student information system for public and non-public 
#  schools from Open Solutions for Education, Inc. web: www.os4ed.com
#
#  openSIS is  web-based, open source, and comes packed with features that 
#  include student demographic info, scheduling, grade book, attendance, 
#  report cards, eligibility, transcripts, parent portal, 
#  student portal and more.   
#
#  Visit the openSIS web site at http://www.opensis.com to learn more.
#  If you have question regarding this system or the license, please send 
#  an email to info@os4ed.com.
#
#  This program is released under the terms of the GNU General Public License  
#  as  published by the Free Software Foundation, version 2 of the License. 
#  See license.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#**************************************************************************** 

*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SD = System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using OSISDynamicTranslation;
//*********************(saikat-16/09/09)****************************************

namespace Student
{
    public partial class Student_PhotoUpload : System.Web.UI.Page
    {
        DynamicTranslation DTL = new DynamicTranslation();
        public static string langto;
        protected void Page_Load(object sender, EventArgs e)
        {
            langto = Session["MLUICulture"].ToString();
            btnUploadPhoto.Text = DTL.Translate(btnUploadPhoto.Text, "en", langto);

        }
        protected void btnUploadPhoto_Click(object sender, EventArgs e)
        {
            Boolean FileSaved = false;
            Boolean FileOK = false;
            int width = 220;
            int height = 220;

            if (UploadFile.HasFile)
            {

                Session["WorkingImage"] = UploadFile.FileName;

                String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();

                String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };

                for (int i = 0; i < allowedExtensions.Length; i++)
                {

                    if (FileExtension == allowedExtensions[i])
                    {
                        FileOK = true;
                    }

                }

            }



            if (FileOK)
            {
                try
                {
                    using (System.Drawing.Bitmap img = ResizeImage(new System.Drawing.Bitmap(UploadFile.PostedFile.InputStream), width, height, ResizeOptions.MaxWidthAndHeight))
                    {
                        string uploadfilename = UploadFile.FileName;
                        //UploadFile.PostedFile.SaveAs(HttpContext.Current.Server.MapPath("~/Garbage Image/" + uploadfilename));
                        img.Save(HttpContext.Current.Server.MapPath("~/Garbage Image/" + uploadfilename));
                        lblMsg.Text = "Your photo was successfully uploaded";

                        FileSaved = true;
                    }
                }
                catch
                {
                    lblMsg.Text = "Photo upload was not successful,please try again.";
                }
            }
            else
            {
                lblMsg.Text = "Cannot accept files of this type.";
            }
            if (FileSaved)
            {

                // pnlUpload.Visible = false;

                pnlCrop.Visible = true;

                imgCrop.ImageUrl = "~/Garbage Image/" + Session["WorkingImage"].ToString();
            }


        }

        protected void btnCrop_Click(object sender, EventArgs e)
        {
            try
            {

                string ImageName = Session["WorkingImage"].ToString();
                int width = 107;
                int height = 115;


                int w = Convert.ToInt32(W.Value);

                int h = Convert.ToInt32(H.Value);

                int x = Convert.ToInt32(X.Value);

                int y = Convert.ToInt32(Y.Value);



                byte[] CropImage = Crop(HttpContext.Current.Server.MapPath("~/Garbage Image/" + ImageName), w, h, x, y);

                using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
                {

                    ms.Write(CropImage, 0, CropImage.Length);

                    using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
                    {

                        using (System.Drawing.Bitmap img = ResizeImage(new System.Drawing.Bitmap(CroppedImage), width, height, ResizeOptions.MaxWidthAndHeight))
                        {
                            string SaveTo = HttpContext.Current.Server.MapPath("~/Garbage Image/" + "crop_" + ImageName);

                            img.Save(SaveTo, img.RawFormat);
                        }

                        //string SaveTo =HttpContext.Current.Server.MapPath("~/Garbage Image/" + "crop_" + ImageName);

                        //CroppedImage.Save(SaveTo, CroppedImage.RawFormat);

                        // pnlCrop.Visible = false;

                        pnlCropped.Visible = true;

                        imgCropped.ImageUrl = "~/Garbage Image/" + "crop_" + ImageName;


                        // Session["StudentImage"] = imgCropped.ImageUrl;

                    }

                }
            }
            catch { }
        }

        static byte[] Crop(string Img, int Width, int Height, int X, int Y)
        {

            try
            {

                using (SD.Image OriginalImage = SD.Image.FromFile(Img))
                {

                    using (SD.Bitmap bmp = new SD.Bitmap(Width, Height, OriginalImage.PixelFormat))
                    {

                        bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);

                        using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
                        {

                            Graphic.SmoothingMode = SmoothingMode.AntiAlias;

                            Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                            Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                            Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, Height, SD.GraphicsUnit.Pixel);

                            MemoryStream ms = new MemoryStream();

                            bmp.Save(ms, OriginalImage.RawFormat);

                            return ms.GetBuffer();

                        }

                    }

                }

            }

            catch (Exception Ex)
            {

                throw (Ex);

            }

        }
        protected void btnDone_Click(object sender, EventArgs e)
        {
            Response.Write("<Script>window.opener.location=window.opener.location;window.close();</Script >");
        }


        //**********************Resize*****************************************
        public enum ResizeOptions
        {
            // Use fixed width & height without keeping the proportions
            ExactWidthAndHeight,

            // Use maximum width (as defined) and keeping the proportions
            MaxWidth,

            // Use maximum height (as defined) and keeping the proportions
            MaxHeight,

            // Use maximum width or height (the biggest) and keeping the proportions
            MaxWidthAndHeight
        }
        public static System.Drawing.Bitmap DoResize(System.Drawing.Bitmap originalImg, int widthInPixels, int heightInPixels)
        {
            System.Drawing.Bitmap bitmap;
            try
            {
                bitmap = new System.Drawing.Bitmap(widthInPixels, heightInPixels);
                using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap))
                {
                    // Quality properties
                    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
                    return bitmap;
                }
            }
            finally
            {
                if (originalImg != null)
                {
                    originalImg.Dispose();
                }
            }
        }

        public static System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap image, int width, int height, ResizeOptions resizeOptions)
        {
            float f_width;
            float f_height;
            float dim;
            switch (resizeOptions)
            {
                case ResizeOptions.ExactWidthAndHeight:
                    return DoResize(image, width, height);

                case ResizeOptions.MaxHeight:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    width = (int)((float)(height) * dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidth:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    height = (int)((float)(width) / dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidthAndHeight:
                    int tmpHeight = height;
                    int tmpWidth = width;
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width && f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;

                    // Check if the width is ok
                    if (f_width < width)
                        width = (int)f_width;
                    height = (int)((float)(width) / dim);
                    // The width is too width
                    if (height > tmpHeight)
                    {
                        if (f_height < tmpHeight)
                            height = (int)f_height;
                        else
                            height = tmpHeight;
                        width = (int)((float)(height) * dim);
                    }
                    return DoResize(image, width, height);
                default:
                    return image;
            }
        }
        //**********************Resize*****************************************

        protected void btnUseOriginal_Click(object sender, EventArgs e)
        {
            try
            {
                int width = 107;
                int height = 115;


                string image = HttpContext.Current.Server.MapPath("~/Garbage Image/" + Session["WorkingImage"].ToString());
                SD.Image UploadedImage = SD.Image.FromFile(image);
                using (System.Drawing.Bitmap img = ResizeImage(new System.Drawing.Bitmap(UploadedImage), width, height, ResizeOptions.MaxWidthAndHeight))
                {
                    string SaveTo = HttpContext.Current.Server.MapPath("~/Garbage Image/" + "original_" + Session["WorkingImage"].ToString());

                    img.Save(SaveTo, img.RawFormat);
                }

                pnlCropped.Visible = true;
                imgCropped.ImageUrl = "~/Garbage Image/original_" + Session["WorkingImage"].ToString();
            }
            catch { }
        }
        protected void btnApplyChanges_Click(object sender, EventArgs e)
        {
            try
            {
                Session["StudentImage"] = imgCropped.ImageUrl;

                string uploadedimage = "~/Garbage Image/" + Session["WorkingImage"].ToString();
                string croppedimage = "~/Garbage Image/" + "crop_" + Session["WorkingImage"].ToString();
                string useoriginalimage = "~/Garbage Image/" + "original_" + Session["WorkingImage"].ToString();

                //******************************(14/10/09')****************************************************
                if (Session["StudentImage"].ToString() == croppedimage)
                {
                    File.Copy(Server.MapPath(Session["StudentImage"].ToString()), Server.MapPath("~/Main Image/" + "crop_" + Session["WorkingImage"].ToString()), true);
                    Session["StudentImage"] = "~/Main Image/" + "crop_" + Session["WorkingImage"].ToString();
                    imgCropped.ImageUrl = Session["StudentImage"].ToString();
                }
                if (Session["StudentImage"].ToString() == useoriginalimage)
                {
                    File.Copy(Server.MapPath(Session["StudentImage"].ToString()), Server.MapPath("~/Main Image/" + "original_" + Session["WorkingImage"].ToString()), true);
                    Session["StudentImage"] = "~/Main Image/" + "original_" + Session["WorkingImage"].ToString();
                    imgCropped.ImageUrl = Session["StudentImage"].ToString();
                }

                imgCrop.Dispose();
                //File.Delete(Server.MapPath(uploadedimage));
                File.Delete(Server.MapPath(useoriginalimage));
                File.Delete(Server.MapPath(croppedimage));
                //******************************(14/10/09')**************************************************** 
            }
            catch { }
        }

    }

}
